package com.tanavlog.common.response;

import com.tanavlog.common.enums.ResultCodeEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 枫花恋
 * @description 无data字段的响应结果
 * @since 2025/7/31 01:47
 */
@Data
@NoArgsConstructor
public class CommonResultSimple {
    // 响应码
    private Integer code;
    // 响应信息
    private String message;
    // 响应时间
    private final Long timestamp = System.currentTimeMillis();
    // 请求链路
    private String path;

    private CommonResultSimple(ResultCodeEnum resultCodeEnum, String path) {

        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
        this.path = path;
    }

    private CommonResultSimple(Integer code, String message, String path) {
        this.code = code;
        this.message = message;
        this.path = path;
    }

    /**
     * 成功响应
     */
    public static CommonResultSimple success() {
        return build(ResultCodeEnum.SUCCESS);
    }

    /**
     * 失败响应
     */
    public static CommonResultSimple fail(ResultCodeEnum resultCodeEnum) {
        return build(resultCodeEnum);
    }
    public static CommonResultSimple fail(String message, Integer code) {
        return build(code, message);
    }


    private static CommonResultSimple build(ResultCodeEnum resultCodeEnum) {
        return new CommonResultSimple(resultCodeEnum, getRequestPath());
    }
    private static CommonResultSimple build(Integer code, String message) {
        return new CommonResultSimple(code, message, getRequestPath());
    }

    /**
     * 获取请求链路
     * @return 请求链路
     */
    private static String getRequestPath() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            return request.getRequestURI();
        }
        return null;
    }

}